<template>
    <div class="out-style">
        <!-- -{{type}}- -->
        <Row :gutter="16">
            <Col span="10">
                <span class="tow-line-font">必须使用Excel模板进行数据导入，禁止对模板表结构进行修改</span>
            </Col>
            <Col span="12">
                <span class="tow-line-font2">
                    <a :href="templateHref" target="_Blank">下载此类数据的Excel模板</a>
                </span>
            </Col>
        </Row>
        <Row type="flex" justify="center">
            <Col span="22" offset="2">
                <div class="step-style">
                    <Steps :current="state">
                        <Step title="上传Excel"></Step>
                        <Step title="预览数据"></Step>
                        <Step title="导入数据"></Step>
                    </Steps>
                </div>
            </Col>
        </Row>
        <div v-show="state === 0">
            <Row>
                <Col>
                    <div class="four-line-font">您将通过上传的Excel文件，批量追加表格数据</div>
                    <div class="four-line-font">导入后只会保留Excel中的数据及通过公式计算后的值，设置的文字颜色等样式、合并的单元格、以及计算公式本身都不会被保留。</div>
                </Col>
            </Row>
            <Row v-if="false">
                <transition name="fade">
                    <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
                        <div v-if="progressPercent == 100">
                            <Icon type="ios-checkmark-circle"/>
                            <span>成功</span>
                        </div>
                    </Progress>
                </transition>
            </Row>
            <Row>
                <Col>
                    <div class="last-line-upload">
                        <Spin size="large" fix v-if="tableLoading"></Spin>
                        <Upload
                                :before-upload="handleBeforeUpload"
                                action=""
                                accept=".xls, .xlsx"
                                type="drag">
                            <div class="upload-tip">
                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                <p>请导入.xls或.xlsx格式的Excel</p>
                            </div>
                        </Upload>
                    </div>
                </Col>
            </Row>
        </div>
        <div v-show="state === 1">
            <Row>
                <div v-if="file !== null" class="ivu-upload-list-file">
                    <Icon type="ios-stats"/>
                    {{ file.name }}
                    <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove"
                          @click.native="handleRemove()"/>
                </div>
            </Row>
            <br>
            <Row>
                <vxe-toolbar custom></vxe-toolbar>
                <vxe-table
                        border
                        show-overflow
                        resizable
                        highlight-hover-row
                        height="500"
                        size="medium"
                        align="center"
                        header-align="center"
                        :cell-style="cellStyle"
                        :loading="tableLoading"
                        :sort-config="{trigger: 'cell'}"
                        :data="tableData">
                    <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
                    <vxe-table-column :field="item.key" :title="item.title" min-width="120"
                                      v-for="(item,index) in tableTitle" :key="index">
                    </vxe-table-column>
                </vxe-table>
            </Row>
            <br>
            <Row type="flex" justify="end">
                <Col span="4">
                    <Button :disabled="nextBtnDisabled" v-show="state === 1" @click="nextStep">下一步</Button>
                </Col>
            </Row>
        </div>
        <div v-show="state === 2">
            <br>
            <Row type="flex" :gutter="16" justify="center">
                <Col span="4">
                    <Button long @click="prevStep">上一步</Button>
                </Col>
                <Col span="4">
                    <Button long icon="ios-cloud-upload-outline" @click="excelBtn">导入到数据库</Button>
                </Col>
            </Row>
        </div>
        <Modal
                v-model="modalShow"
                title="提示"
                :loading="modalLoading"
                @on-ok="modalSubmit">
            <br>
            <h3 style="text-align: center">确认开始数据导入？</h3>
        </Modal>
        <Modal v-model="modalShow2" width="600" :closable="false">
            <div slot="header" style="color:#f60;text-align:center">
                <h3>导入数据在库中已存在，请删除后再进行导入</h3>
            </div>
            <div style="height: 300px; overflow-y: scroll; text-align: center;">
                <div style="margin-bottom: 5px">
                    <span style="font-weight: bold; display: inline-block;width: 20%;">公司名称</span>
                    <span style="font-weight: bold; display: inline-block;width: 20%;">姓名</span>
                    <span style="font-weight: bold; display: inline-block;width: 40%;">身份证号</span>
                    <span style="font-weight: bold; display: inline-block;width: 20%;">手机号</span>
                </div>
                <div v-for="(item, index) in troubleData" :key="index">
                    <span style="display: inline-block;width: 20%;">{{item.work_name}}</span>
                    <span style="display: inline-block;width: 20%;">{{item.name}}</span>
                    <span style="display: inline-block;width: 40%;">{{item.card_no ? item.card_no.replace(/^(.{6})(?:\d+)(.{4})$/, '$1****$2') : ''}}</span>
                    <span style="display: inline-block;width: 20%;">{{item.phone ? item.phone.replace(/^(.{3})(?:\w+)(.{4})$/, '$1****$2') : ''}}</span>
                </div>
            </div>
            <div slot="footer">
                <Button type="error" size="large" @click="modalShow2 = false">确定</Button>
                <Button type="success" size="large" @click="delPepetitionIdcardData">忽略数据导入</Button>
            </div>
        </Modal>
        <Modal v-model="modalShow3" width="600" :closable="false">
            <div slot="header" style="color:#f60;text-align:center">
                <h3>以下数据导入失败，部分信息如下，请整理后再进行导入</h3>
            </div>
            <div style="height: 300px; overflow-y: scroll; text-align: center;">
                <div style="margin-bottom: 5px">
                    <span v-if="type == 'place'" style="font-weight: bold; display: inline-block;width: 20%;">场所名称</span>
                    <span v-if="type == 'place'" style="font-weight: bold; display: inline-block;width: 40%;">场所地址</span>
                    <span v-if="type == 'handle'" style="font-weight: bold; display: inline-block;width: 40%;">身份证号</span>
                    <span style="font-weight: bold; display: inline-block;width: 20%;">联系人姓名</span>
                    <span style="font-weight: bold; display: inline-block;width: 20%;">联系电话</span>
                </div>
                <div v-for="(item, index) in failData" :key="index">
                    <span v-if="type == 'place'" style="display: inline-block;width: 20%;">{{item.place_name}}</span>
                    <span v-if="type == 'place'" style="display: inline-block;width: 40%;">{{item.place_address}}</span>
                    <span v-if="type == 'handle'" style="display: inline-block;width: 40%;">{{item.card_no ? item.card_no.replace(/^(.{6})(?:\d+)(.{4})$/, '$1****$2') : ''}}</span>
                    <span style="display: inline-block;width: 20%;">{{item.name}}</span>
                    <span style="display: inline-block;width: 20%;">{{item.mobile}}</span>
                </div>
            </div>
            <div slot="footer">
                <Button type="error" size="large" long @click="modalShow3 = false">确定</Button>
            </div>
        </Modal>
        <Modal v-model="modalShow4" width="600" :closable="false">
            <div slot="header" style="color:#f60;text-align:center">
                <h3>以下数据导入失败，部分信息如下，请整理后再进行导入</h3>
            </div>
            <div style="height: 300px; overflow-y: scroll; text-align: center;">
                <div style="margin-bottom: 5px">
                    <span style="font-weight: bold; display: inline-block;width: 30%;">姓名</span>
                    <span style="font-weight: bold; display: inline-block;width: 40%;">证件号</span>
                    <span style="font-weight: bold; display: inline-block;width: 30%;">国籍</span>
                </div>
                <div v-for="(item, index) in failData" :key="index">
                    <span style="display: inline-block;width: 30%;">{{item.name}}</span>
                    <span style="display: inline-block;width: 40%;">{{item.card_no}}</span>
                    <span style="display: inline-block;width: 30%;">{{item.import_nation_name}}</span>
                </div>
            </div>
            <div slot="footer">
                <Button type="error" size="large" long @click="modalShow4 = false">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import excel from '@/libs/excel'
import { validateUniqueCardnoList, saveExcelData } from '@/api/worker'
import excelTemplate from './excel-template'
import { validateWorker, validatePlace, validateHandle, validateWhiteForeign } from './validateData'
import { handleWorker, handlePlace } from './handleData'

export default {
  name: 'excelActionNew',
  props: {
    type: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      state: 0,
      modalShow: false,
      modalShow2: false, // 旧版显示（具有忽略导入功能 2个接口 先调查询 再插入）
      modalShow3: false, // 新版显示（1个接口 错误数据直接带回）
      modalShow4: false, // 新版显示（白名单）
      troubleData: [], // 问题数据内容
      failData: [], // 失败数据内容
      modalLoading: true,
      uploadLoading: false,
      showRemoveFile: false,
      file: null,
      tableData: [],
      saveTableData: [],
      tableTitle: [],
      progressPercent: 0,
      showProgress: false,
      tableLoading: false,
      nextBtnDisabled: false,
      templateHref: '',
      tableToolbar: {
        buttons: [
          {
            code: 'mark_cancel',
            name: 'app.body.button.markCancel',
            status: 'perfect',
            icon: 'fa fa-trash-o vxe-danger-color'
          }
        ],
        perfect: true,
        resizable: true,
        custom: {
          icon: 'fa fa-cog'
        }
      }
    }
  },
  methods: {
    cellStyle ({ row, rowIndex, column, columnIndex }) {
      if (!this.$common.xeUtils.isEmpty(row.cellClassName[column.property])) {
        if (row.cellClassName[column.property] === 'trouble-cell') {
          return {
            backgroundColor: '#FFEFE6',
            color: '#ED4014'
            // backgroundColor: '#187'
          }
        } else if (row.cellClassName[column.property] === 'trouble-cell-repeat') {
          return {
            backgroundColor: '#187',
            color: '#fff'
          }
        }
      }
    },
    initTemplate () {
      switch (this.type) {
        case 'worker':
          this.templateHref = excelTemplate.workerTemplate
          break
        case 'place':
          this.templateHref = excelTemplate.placeTemplate
          break
        case 'handle':
          this.templateHref = excelTemplate.handleTemplate
          break
        case 'whiteForeign':
          this.templateHref = excelTemplate.whiteForeignTemplate
          break
      }
    },
    prevStep () {
      this.state = 1
    },
    nextStep () {
      this.state = 2
    },
    excelBtn () {
      this.modalShow = true
    },
    // 身份证号组装处理
    autoCardnoHandle () {
      let cardnos = []
      this.tableData.forEach(item => {
        if (item.card_no) {
          cardnos.push(item.card_no)
        }
      })
      return cardnos
    },
    // 导入数据身份证号唯一校验
    validateUniqueCardno (val) {
      this.modalLoading = true
      validateUniqueCardnoList({ cardnos: val }).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          if (data.data.length > 0) {
            this.troubleData = data.data
            this.modalShow = false
            this.modalLoading = false
            this.modalShow2 = true
          } else {
            this.saveExcelDataAction()
          }
        } else {
          this.modalLoading = false
          this.error(data)
        }
      })
    },
    delPepetitionIdcardData () {
      let idCardOList = []
      let saveData = []
      this.troubleData.forEach(item => {
        idCardOList[item.card_no.trim()] = true
      })
      this.saveTableData.forEach(item => {
        if (idCardOList[item.card_no.trim()] !== true) {
          saveData.push(item)
        }
      })
      this.saveTableData = saveData
      this.saveExcelDataAction()
    },
    // 保存导入数据
    saveExcelDataAction () {
      this.modalLoading = true
      const tableData = this.saveTableData
      let param = {}
      switch (this.type) {
        case 'worker':
          param = { type: this.type, dataList: tableData }
          break
        case 'place':
          param = { type: this.type, dataList: tableData }
          break
        case 'handle':
          param = { type: this.type, dataList: tableData }
          break
        case 'whiteForeign':
          param = { type: this.type, dataList: tableData }
          break
      }
      saveExcelData(param).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.modalLoading = false
          this.success(tableData.length)
          this.modalShow = false
          if (data.data.falseList && data.data.falseList.length > 0 && this.type !== 'whiteForeign') {
            this.modalShow3 = true
            this.failData = data.data.falseList
          } else if (data.data.falseList && data.data.falseList.length > 0 && this.type === 'whiteForeign') {
            this.modalShow4 = true
            this.failData = data.data.falseList
          }
        } else {
          this.modalLoading = false
          this.error(data)
        }
      }).catch(ret => {
        this.modalLoading = false
        this.$Message.error('操作失败')
      })
    },
    modalSubmit () {
      if (this.tableData.length === 0) {
        this.$Notice.warning({
          title: '请上传excel文件'
        })
      } else {
        switch (this.type) {
          case 'worker':
            const cardnos = this.autoCardnoHandle()
            this.validateUniqueCardno(cardnos)
            break
          case 'place':
            this.saveExcelDataAction()
            break
          case 'handle':
            this.saveExcelDataAction()
            break
          case 'whiteForeign':
            this.saveExcelDataAction()
            break
        }
      }
    },
    success (data) {
      if (data) {
        this.$Message.success('操作成功,共添加' + data + '条数据')
      } else {
        this.$Message.success('操作成功')
      }
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    },
    initUpload () {
      this.file = null
      this.state = 0
      this.tableData = []
      this.tableTitle = []
      this.showProgress = false
    },
    handleUploadFile () {
      this.initUpload()
    },
    handleRemove () {
      this.initUpload()
      this.$Message.info('上传的文件已删除！')
      this.state = 0
    },
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 读取文件
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.uploadLoading = true
        this.tableLoading = true
        this.state = 0
        this.showProgress = true
      }
      // reader.onprogress = e => {
      //   this.progressPercent = Math.round(e.loaded / e.total * 100)
      // }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const { header, results } = excel.read(data, 'array')
        const tableTitle = header.map(item => {
          return { title: results[0][item], key: item, minWidth: 200, align: 'center' }
        })
        this.tableData = this.$common.xeUtils.clone(results)
        this.tableData.splice(0, 2) // 默认删除前两行数据

        let saveTableData = []
        let repeatArr = []
        switch (this.type) {
          case 'worker':
            this.tableData.forEach((item, index) => {
              item.cellClassName = { work_no: '', type: '', health_type: '', person_type: '' }
              if (repeatArr[item.card_no]) {
                item.cellClassName.card_no = 'trouble-cell-repeat'
              } else {
                repeatArr[item.card_no] = true
              }
              let result = validateWorker(item, index)
              item = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(handleWorker(this.$common.xeUtils.clone(item)))
            })
            break
          case 'place':
            this.tableData.forEach((item, index) => {
              item.cellClassName = { place_type: '' }
              let result = validatePlace(item, index)
              item = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(handlePlace(this.$common.xeUtils.clone(item)))
            })
            break
          case 'handle':
            this.tableData.forEach((item, index) => {
              item.cellClassName = {}
              if (repeatArr[item.card_no]) {
                item.cellClassName.card_no = 'trouble-cell-repeat'
              } else {
                repeatArr[item.card_no] = true
              }
              let result = validateHandle(item, index)
              item = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(this.$common.xeUtils.clone(item))
            })
            break
          case 'whiteForeign':
            this.tableData.forEach((item, index) => {
              item.cellClassName = {}
              if (repeatArr[item.card_no]) {
                item.cellClassName.card_no = 'trouble-cell-repeat'
              } else {
                repeatArr[item.card_no] = true
              }
              let result = validateWhiteForeign(item, index)
              item = result.item
              if (result.error === true) {
                this.nextBtnDisabled = true
              }
              saveTableData.push(this.$common.xeUtils.clone(item))
            })
            break
        }
        this.saveTableData = saveTableData

        this.tableTitle = tableTitle
        this.uploadLoading = false
        this.tableLoading = false
        this.showRemoveFile = true
        this.state = 1
      }
    }
  },
  mounted () {
    this.initTemplate()
    // console.log('传入的类型', this.type)
  }
}
</script>

<style scoped>
    .out-style {
        padding: 10px;
        padding-bottom: 50px;
    }

    .tow-line-font {
        font-size: 14px;
    }

    .tow-line-font2 {
        text-decoration: underline;
        font-size: 14px;
        color: #40A7FF;
        font-weight: 600;
        cursor: pointer;
    }

    .step-style {
        margin-top: 30px;
        margin-bottom: 30px;
    }

    .four-line-font {
        font-size: 14px;
    }

    .last-line-upload {
        margin-top: 20px;
    }

    .last-line-upload >>> .ivu-upload-drag {
        height: 230px;
        background: #fff;
        border: 1px dashed #dcdee2;
        border-radius: 4px;
        text-align: center;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: border-color .2s ease;
    }

    .upload-tip {
        padding-top: 75px;
    }

    /deep/ .ivu-table .trouble-cell {
        /*background-color: #FFEFE6;*/
        color: #ED4014;
    }

    /deep/ .ivu-table .trouble-cell-repeat {
        background-color: #FFEFE6;
        color: #ED4014;
    }
</style>
